package com.i2works.smartluolong.web.service.user.impl;


import com.i2works.smartluolong.utils.basecommon.BaseCommonServiceImpl;
import com.i2works.smartluolong.utils.exception.DAOException;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.dal.user.dao.IUserRoleDAO;
import com.i2works.smartluolong.web.entity.user.UserRoleDO;
import com.i2works.smartluolong.web.entity.user.UserRoleQuery;
import com.i2works.smartluolong.web.entity.user.UserRoleResDO;
import com.i2works.smartluolong.web.service.user.IUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * 会员角色表实现类
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2016/2/26 14:30
 */
@Service("userRoleService")
public class UserRoleServiceImpl extends BaseCommonServiceImpl<UserRoleQuery,UserRoleDO> implements IUserRoleService {

    private final IUserRoleDAO userRoleDAO;

    @Autowired
    public UserRoleServiceImpl(IUserRoleDAO userRoleDAO) {
        this.userRoleDAO = userRoleDAO;
    }


    /**
     * 权限添加
     */
    private void saveUserRoleRes(List<String> resList,UserRoleDO postUserRole) throws DAOException{
        UserRoleResDO userRoleResDO = new UserRoleResDO();
        userRoleResDO.setRoleId(postUserRole.getId());
        for (String resId : resList) {
            userRoleResDO.setResId(Integer.parseInt(resId));
            userRoleDAO.saveRoleRes(userRoleResDO);
        }
    }

    /**
     * 保存会员角色
     */
    @Override
    public void save(UserRoleDO userRoleDO) throws ServiceException {
        try {
            UserRoleDO postUserRole;
            if (userRoleDO.getId() != 0 && userRoleDO.getId() != null) {
                //更新
                userRoleDAO.update(userRoleDO);
                //权限,先删除,再添加
                userRoleDAO.deleteRoleRes(userRoleDO.getId());
                //设置role
                postUserRole = userRoleDO;
            } else {
                //新增
                userRoleDO.setCreateName(userRoleDO.getUpdateName());
                userRoleDAO.save(userRoleDO);
                //设置role
                postUserRole = userRoleDO;
            }
            //权限添加
            List<String> resList = userRoleDO.getResList();
            System.out.println(resList);
            if (resList != null && resList.size() > 0) {
                saveUserRoleRes(resList, postUserRole);
            }
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 查询某会员的所有角色
     */
    @Override
    public Set<UserRoleDO> queryUserRoleList(UserRoleQuery query) throws ServiceException {
        try {
            return userRoleDAO.queryUserRoleList(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

}
